package treemap.demo03;

import java.util.TreeMap;

/**
 * "aababcabcdabcde",获取字符串中每一个字符出现的次数；
 * 要求结果:a(5)b(4)c(3)d(2)e(1)
 */
public class TreeMapDemo {
    public static void main(String[] args) {

        //创建一个字符串
        String s = "aababcabcdabcde";
        //将字符串变成字符数组
        char[] chars = s.toCharArray();
        //将数组中的对象添加到TreeMap集合中
        TreeMap<Character, Integer> treeMap = new TreeMap<>();


        Integer index;
        for (int i = 0; i < chars.length; i++) {

            boolean empty = treeMap.isEmpty();

            boolean b = treeMap.containsKey(chars[i]);
            if(empty){
                treeMap.put(chars[i],1);
            }
            if (b){
                index = treeMap.get(chars[i]);
                treeMap.put(chars[i],index+1);
            }else {
                treeMap.put(chars[i],1);
            }
            /*treeMap.isEmpty()?treeMap.put(chars[i],1):
                    treeMap.containsKey(chars[i])?*/
        }
        StringBuilder stringBuilder = new StringBuilder();

        treeMap.forEach((key,value)-> stringBuilder.append(key + "("+value+")"));

        String s1 = stringBuilder.toString();

        System.out.println(s1);
    }
}
